﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace SIMSProject.ControlTemplates.SIMSProject
{
    public partial class MaterialAdding : UserControl, ICallbackEventHandler
    {
        public string ParentListName;

        public string returnMessage = string.Empty;
        
        public string displayMode = string.Empty;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            if (SPContext.Current.FormContext.FormMode == SPControlMode.Edit || SPContext.Current.FormContext.FormMode == SPControlMode.New)
            {
                SPContext.Current.FormContext.OnSaveHandler += this.CustomSaveHandler;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            string callBackReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");
            string callbackScript;
            callbackScript = "function CallServer(arg, context)" +
                "{ " + callBackReference + ";}";
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);

            if (!Page.IsPostBack)
            {
                LoadData();
            }

            DataTable MaterialTable = (DataTable)Session[this.hdfSessionName.Value];
            
            if (ParentListName == "Material Request")
            {
                if (SPContext.Current.FormContext.FormMode == SPControlMode.Display || (SPContext.Current.FormContext.FormMode == SPControlMode.Edit && !string.Equals(SPContext.Current.Web.CurrentUser.LoginName, this.GetRequestorUser().LoginName)) || (SPContext.Current.FormContext.FormMode == SPControlMode.Edit && !string.Equals(Convert.ToString(SPContext.Current.Item["Status"]), "Pendding")))
                {
                    this.dgMaterialListDisplay.Visible = true;
                    this.dgMaterialListDisplay.DataSource = MaterialTable;
                    this.dgMaterialListDisplay.DataBind();
                }
                else
                {
                    if (this.dgMaterialList.EditItemIndex == -1)
                    {
                        this.dgMaterialList.Visible = true;
                        this.addNewMaterial.Visible = true;
                        this.dgMaterialList.DataSource = MaterialTable;
                        this.dgMaterialList.DataBind();
                    }
                }
            }
            else if (ParentListName == "Material Tracking")
            {
                if (displayMode == "Display")
                {
                    this.dgMaterialListDisplay.Visible = true;
                    this.addNewMaterial.Visible = false;
                    this.dgMaterialListDisplay.DataSource = MaterialTable;
                    this.dgMaterialListDisplay.DataBind();
                }
                else
                {
                    if (this.dgMaterialList.EditItemIndex == -1)
                    {
                        this.dgMaterialList.Visible = true;
                        this.addNewMaterial.Visible = true;
                        this.dgMaterialList.DataSource = MaterialTable;
                        this.dgMaterialList.DataBind();
                    }
                }
            }
        }

        private SPUser GetRequestorUser()
        {
            string requestor = Convert.ToString(SPContext.Current.Item["Created By"]);
            SPFieldUserValue value = new SPFieldUserValue(SPContext.Current.Web, requestor);
            return value.User;
        }

        public void SetSessionName(string name)
        {
            this.hdfSessionName.Value = name;
        }


        private void LoadData()
        {
            DataTable MaterialTable = new DataTable();
            MaterialTable.Columns.Add("stt", typeof(int));
            MaterialTable.Columns.Add("id", typeof(int));
            MaterialTable.Columns.Add("MaterialName", typeof(string));
            MaterialTable.Columns.Add("MaterialCode", typeof(string));
            MaterialTable.Columns.Add("Quantity", typeof(int));

            int id = SPContext.Current.Item.ID;
            if (id != 0)
            {
                SPList childList = SPContext.Current.Web.Lists[this.ParentListName + " Detail"];
                SPQuery query = new SPQuery();

                query.Query = "<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + id + "</Value></Eq></Where>";
                if (childList.GetItems(query).Count > 0)
                {
                    SPListItemCollection items = childList.GetItems(query);
                    for (int i = 0; i < items.Count; i++)
                    {
                        DataRow row = MaterialTable.NewRow();
                        row["stt"] = i + 1;
                        row["id"] = items[i]["Material Id"];
                        row["MaterialName"] = items[i]["Material Name"];
                        row["MaterialCode"] = items[i]["Material Code"];
                        row["Quantity"] = items[i]["Quantity"];
                        MaterialTable.Rows.Add(row);
                    }
                }
            }

            Session[this.hdfSessionName.Value] = MaterialTable;
        }

        private void CustomSaveHandler(object o, EventArgs e)
        {

        }

        /// <summary>
        /// Returns the results of a callback event that targets a control.
        /// </summary>
        /// <returns>The result of the callback.</returns>
        public string GetCallbackResult()
        {
            return returnMessage;
        }

         /// <summary>
        /// Processes a callback event that targets a control.
        /// </summary>
        /// <param name="eventArgument">A string that represents an event argument to pass to the event handler.</param>
        public void RaiseCallbackEvent(string eventArgument)
        {
            string[] value = eventArgument.Split('|');

            int id = 0;
            int index = -1;
            int quantity = 0;

            int temp = 0;

            Int32.TryParse(value[0], out id);
            Int32.TryParse(value[1], out quantity);
            if (quantity == 0)
            {
                returnMessage = "The quantity input is over range";
                return;
            }
            if (id!=0)
            {
                SPListItem material = SPContext.Current.Web.Lists["Material"].GetItemById(id);

                int materialQuantity = 0;
                Int32.TryParse(Convert.ToString(material["Quantity"]), out materialQuantity);

                DataTable MaterialTable = (DataTable)Session[this.hdfSessionName.Value];

                for (int i = 0; i < MaterialTable.Rows.Count; i++)
                {
                    if (string.Equals(Convert.ToString(material["Title"]), MaterialTable.Rows[i]["MaterialName"]))
                    {
                        Int32.TryParse(Convert.ToString(MaterialTable.Rows[i]["Quantity"]), out temp);
                        quantity = quantity + temp;
                        index = i;
                    }
                }

                if (temp > 0)
                {
                    MaterialTable.Rows[index]["Quantity"] = quantity;
                }

                if (temp == 0)
                {
                    DataRow row = MaterialTable.NewRow();
                    row["stt"] = MaterialTable.Rows.Count + 1;
                    row["id"] = material.ID;
                    row["MaterialName"] = Convert.ToString(material["Title"]);
                    row["MaterialCode"] = Convert.ToString(material["Material Code"]);
                    row["Quantity"] = quantity;
                    MaterialTable.Rows.Add(row);
                }

                Session[this.hdfSessionName.Value] = MaterialTable;
            }
        }

        protected void dgMaterialList_DeleteCommand(object source, DataGridCommandEventArgs e)
        {
            DataTable materialTable = (DataTable)Session[this.hdfSessionName.Value];

            materialTable.Rows.RemoveAt(e.Item.ItemIndex);

            materialTable = this.ReBuildDataTable(materialTable);

            Session[this.hdfSessionName.Value] = materialTable;
            this.dgMaterialList.DataSource = materialTable;
            this.dgMaterialList.DataBind();
        }

        protected void dgMaterialList_EditCommand(object source, DataGridCommandEventArgs e)
        {
            this.dgMaterialList.EditItemIndex = e.Item.ItemIndex;
            DataTable materialTable = (DataTable)Session[this.hdfSessionName.Value];
            this.dgMaterialList.DataSource = materialTable;
            this.dgMaterialList.DataBind();
        }

        protected void dgMaterialList_CancelCommand(object source, DataGridCommandEventArgs e)
        {
            this.dgMaterialList.EditItemIndex = -1;
            DataTable materialTable = (DataTable)Session[this.hdfSessionName.Value];
            this.dgMaterialList.DataSource = materialTable;
            this.dgMaterialList.DataBind();
        }

        protected void dgMaterialList_UpdateCommand(object source, DataGridCommandEventArgs e)
        {
            int quantity = 0;
            Int32.TryParse(((TextBox)e.Item.Cells[3].Controls[0]).Text, out quantity);

            if (quantity == 0)
            {
                this.Page.Response.Write("<script type='text/javascript'>window.alert('The value is not an integer');</script>");
                return;
            }
            else if (quantity < 0)
            {
                this.Page.Response.Write("<script type='text/javascript'>window.alert('The value must is a postive number');</script>");
                return;
            }

            DataTable materialTable = (DataTable)Session[this.hdfSessionName.Value];

            int id = 0;
            Int32.TryParse(Convert.ToString(materialTable.Rows[e.Item.ItemIndex]["id"]), out id);


            materialTable.Rows[e.Item.ItemIndex]["Quantity"] = quantity;

            Session[this.hdfSessionName.Value] = materialTable;
            this.dgMaterialList.EditItemIndex = -1;
            this.dgMaterialList.DataSource = materialTable;
            this.dgMaterialList.DataBind();
        }

        private DataTable ReBuildDataTable(DataTable table)
        {
            for (int i = 0; i < table.Rows.Count; i++)
            {
                table.Rows[i]["stt"] = i + 1;
            }
            
            return table;
        }
    }
}
